package com.shuiyun.chat.handler;

import com.google.gson.Gson;
import com.shuiyun.chat.entity.message.ReceiveGroupMessage;
import com.shuiyun.chat.entity.message.SendGroupMessage;
import com.shuiyun.chat.entity.vo.ChatGroupVO;
import com.shuiyun.chat.enums.ChatSessionKey;
import com.shuiyun.chat.service.ChatGroupService;
import com.shuiyun.chat.service.UserService;
import com.shuiyun.chat.utils.BeanUtil;
import com.shuiyun.chat.utils.RedisUtil;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Set;

/**
 * @author shuiyun
 * @program chatServer
 * @description 服务器接收群消息发送处理
 * @create 2021-05-14 17:40
 **/
@Slf4j
@Component
@ChannelHandler.Sharable
public class SendGroupMessageHandler extends SimpleChannelInboundHandler<SendGroupMessage> {

    @Autowired
    private ChatGroupService groupService;
    @Autowired
    private UserService userService;
    @Autowired
    private RedisUtil redisUtil;

    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, SendGroupMessage sendGroupMessage) throws Exception {
        // 获取群信息
        ChatGroupVO chatGroupVO = groupService.get(sendGroupMessage.getGroupId());
        // 获取群友通道
        Set<String> users = chatGroupVO.getUsers();
        users.forEach(user -> {
            // 跳过自己
            if(user.equals(sendGroupMessage.getUserName())){
                return;
            }
            Channel channel = userService.getChannelByUserName(user);
            // 如果对方不在线 则进行数据缓存
            ReceiveGroupMessage receiveGroupMessage = BeanUtil.copyProperties(sendGroupMessage, ReceiveGroupMessage.class);
            receiveGroupMessage.setGroupName(chatGroupVO.getName());
            receiveGroupMessage.setReceiverName(user);
            if (null == channel){
                redisUtil.rightPush(ChatSessionKey.groupChat.getKey() + user,new Gson().toJson(receiveGroupMessage));
            }else{
                channel.writeAndFlush(receiveGroupMessage);
            }
        });
    }
}
